# Copyright (c) 2010, College Center for Library Automation

# See the included Copyright.txt file for full license

#

use strict;
use warnings;
#use PDF::ReportWriter;

require "ReportWriter150.pm";
use avsCommon;

use DBI;
use DBD::ODBC;
use Date::Calc qw(Decode_Month Today Month_to_Text Month_to_Text English_Ordinal);


my ($dbhstats, $sqlstats, $sthstats);
my ($vendor, $source, $month, @searches, $type);
my @dbdata = ();

paramscheck();
my ($month_cnt, $year_start, $fyend, $fystart);

if ($begmonth <= 6) {
	$fyend = $begyear;
	$fystart = $begyear - 1;
}
else {
	$fyend = $begyear + 1;
	$fystart = $begyear;
}

print "#info: fiscal year $fystart - $fyend\n";

$dbhstats = DBI->connect('dbi:ODBC:AutomatedVendorStats' ,,, { 'PrintError' => 1, 'RaiseError' => 1 })
	or die '#error: dbhstats connect: ' . DBI->errstr;
	
$sqlstats = qq/EXEC GetFYStatsPivot ?,0/;
$sthstats = $dbhstats->prepare($sqlstats);

setupXML();

$sthstats->execute($endyear.'-'.$endmonth.'-'.$endday);

@dbdata = @{$sthstats->fetchall_arrayref()};

my $rw = PDF::ReportWriter->new();
$rw->render_report("../temp/Rpt_L011.tmp",  \@dbdata);
my $rptname = "../Reports/L011_M_ALL___". sprintf('%04d%02d%02d', $endyear, $endmonth, $endday);
$rw->{destination}=$rptname.'.pdf';
$rw->save();

# prepare to build a csv file after pdf file
use Text::CSV;
my $csv=Text::CSV->new();

# open and send data to the csv file
open CSV, ">:utf8", "$rptname.csv";
print CSV 'Vendor,DataSource,SW', map (',"'.$fystart.'-'.$_.'"', (7..12)),map (',"'.$fyend.'-'.$_.'"', (1..6)),",FY Total\n";

foreach my $datarow (@dbdata) {
	if ($csv->combine(@{$datarow})) {
		print CSV $csv->string(),"\n";
	}
}

close CSV;

$sthstats->finish if ($sthstats);
$dbhstats->disconnect if ($dbhstats);

sub setupXML {
	use XML::Twig;
	use IO::File;

	$month_cnt = 1;
	$year_start = $fystart;

	my $file = 'Rpt_L011.xml';
	my $twig= new XML::Twig(
		TwigHandlers => {
			'page/header/cell[@name="month"]' => \&heading_handler_months,
			'page/header/cell[@name="rundate"]' => \&heading_handler_rundate},
		TwigRoots => {report => 1});
	$twig->parsefile($file);

	my $fh = new IO::File("../temp/Rpt_L011.tmp", "w");
	$twig->print($fh);
	close $fh;

	# put the FY on the month abbvreviations
	sub heading_handler_months {
		my ($twig_obj, $month_cell) = @_;
		my $month_text = $month_cell->first_child_text('text');

		$year_start++ if $month_cnt++ == 7;

		$month_cell->first_child('text')->set_text($month_text.'-'.substr("0$year_start",-2));
	}

	# put the college name in the month abbvreviations
	sub heading_handler_rundate {
		my ($twig_obj, $rundate_cell) = @_;
		my ($tyear, $tmonth, $tday) = Today;
		$rundate_cell->first_child('text')->set_text(Month_to_Text($tmonth).' '.$tday.', '.$tyear);
	}
}